﻿using Newtonsoft.Json.Linq;
using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace EasyMirai.MiraiJar
{
    public class MiraiJAR:IDisposable
    {
        private WebClient wc = new WebClient();
        private string downloadurl;
        private string version;
        private string name;
        private bool plugin;
        private bool Downloading = false;
        /// <summary>
        /// New instance of MiraiJAR
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="author"></param>
        /// <param name="shadow">Shows that this file should be downloaded from mirai shadow repos</param>
        public MiraiJAR(string fileName, string author, bool shadow = false)
        {
            try
            {
                wc.DownloadFileCompleted += Wc_DownloadFileCompleted;
                wc.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36");
                name = fileName;
                if (name == "mirai-console-pure" || name == "mirai-core-qqandroid") 
                {
                    //Unable to find the public github api for this
                    version = wc.DownloadString("https://raw.githubusercontent.com/project-mirai/mirai-repo/master/shadow/latest.txt").Split('\n').Where(x => x.Contains(name)).First().Split(':')[1];
                    downloadurl = "https://github.com/project-mirai/mirai-repo/raw/master/shadow/" + name + "/" + name + "-" + version + ".jar";
                    plugin = false;
                }
                else
                {
                    var json = wc.DownloadString("https://api.github.com/repos/" + author + "/" + fileName + "/releases/latest");
                    JObject obj = JObject.Parse(json);
                    if (!shadow)
                    {
                        downloadurl = obj.Value<JArray>("assets")[0].Value<string>("browser_download_url");
                    }
                    else
                    {
                        downloadurl = "https://github.com/project-mirai/mirai-repo/raw/master/shadow/" + name + "/" + name + "-" + obj.Value<string>("tag_name") + ".jar";
                    }
                    plugin = !shadow;
                    version = obj.Value<string>("tag_name");
                }
            }
            catch(Exception ex)
            {
                File.WriteAllText("error" + DateTime.Now.ToString("yyyy_mm_dd_HH_mm_ss")+".log", ex.ToString() + "\nAt " + fileName);
            }

        }

        private void Wc_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            Downloading = false;
        }

        public bool NewestCheck(string localFilePath)
        {
            var file = localFilePath.Split('\\').Last();
            if (file == name + "-" + version + ".jar")
            {
                return true;
            }
            else
            {
                //Check if we have more latest version here
                var currentversion = file.Replace(name + "-", "").Replace(".jar","");
                if (String.Compare(currentversion, version, true) > 0)
                {
                    return true;
                }
                return false;
            }
        }

        public async void Download()
        {
            if(downloadurl == null)
            {
                return;
            }
            if (plugin)
            {
                if (!Directory.Exists("plugins"))
                {
                    Directory.CreateDirectory("plugins");
                }
                wc.DownloadFileAsync(new Uri(downloadurl), "plugins\\"+name + "-" + version + ".jar");
            }
            else
            {
                wc.DownloadFileAsync(new Uri(downloadurl), name + "-" + version + ".jar");
            }
            Downloading = true;
            do
            {
                await Task.Delay(1000);
            }
            while (Downloading);
        }

        public void Dispose()
        {
            wc.Dispose();
        }

        public string DownloadUrl
        {
            get
            {
                return downloadurl;
            }
        }

        public string FileName
        {
            get
            {
                return name;
            }
        }
        public bool DownloadingFile
        {
            get
            {
                return Downloading;
            }
        }
    }
}
